/*
 * @(#)NoResponseWorkflowHandler.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.core;

import java.sql.Connection;
import java.util.Date;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.Utility;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;
import com.dcivision.workflow.web.MaintWorkflowProgressForm;
/**
 * NoResponseWorkflowHandler.java
 * 
 * This class is responsible for handling overdued task. This class is not supposed
 * to be initialized and used by your own code as it relies on the scheduler.  
 * 
 * @author Rollo Chan
 * @company DCIVision Limited
 * @creation date 06/10/2003
 * @version $Revision: 1.14.2.2 $
 * @see com.dcivision.workflow.core.WorkflowOperationManager#scheduleNoResponseAction
 */
public class NoResponseWorkflowHandler implements Job {
  
  public static final String REVISION = "$Revision: 1.14.2.2 $";
  
  private Connection conn = null;
  private SessionContainer sessionCon = null;
  protected Log log = LogFactory.getLog(this.getClass().getName());
  private Vector scheduledJobVec = new Vector();
  
  private final Integer workflowAutomaticUserID = new Integer(0);
  
  /** Creates a new instance of NoResponseWorkflowHandler */
  public NoResponseWorkflowHandler() {
  }
  /**
   * This is not supposed to be invoked by your own code.
   * 
   * @param context The JobExecutionContext object
   * @throws JobExecutionException
   */
  public void execute(JobExecutionContext context) throws JobExecutionException {
    try{
      this.conn = DataSourceFactory.getConnection();
      this.sessionCon = new SessionContainer();
      
      UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionCon, conn);
      this.sessionCon.setUserRecord((UserRecord) userRecordDAO.getObjectByID(workflowAutomaticUserID));
      
      log.info("--------------Start NoResponseWorkflowHandler-----------" );
      WorkflowStep workflowStep = (WorkflowStep)context.getJobDetail().getJobDataMap().get("WORKFLOW_STEP");
      WorkflowProgress workflowProgress = (WorkflowProgress)context.getJobDetail().getJobDataMap().get("WORKFLOW_PROGRESS");
      log.info("--------------NoResponseWorkflowHandler:" + context.getJobDetail().getFullName() + " executed.[" + new Date() + "]");
      String onNoResponseAction = workflowStep.getOnNoResponseAction();
      
      //get the current status of the workflow progess
      WorkflowProgressDAObject progressDAO = new WorkflowProgressDAObject(this.sessionCon, this.conn);
      log.debug(workflowProgress.getID());
      try {
        workflowProgress = (WorkflowProgress) (progressDAO.getObjectByID(workflowProgress.getID()));

      }catch(Exception ex){
        log.error(ex, ex);
      }      

      if (WorkflowProgress.STATUS_REVOKE.equals(workflowProgress.getStatus())) {

        WorkflowProgress tmpWorkflowProgress = progressDAO.getObjectByTrackIDStepIDStatus(
            workflowProgress.getTrackID(), workflowProgress.getWorkflowStepID());
        if (!Utility.isEmpty(tmpWorkflowProgress)) {
          workflowProgress = tmpWorkflowProgress;
        }
      }

      String progressStatus = workflowProgress.getStatus();
      
      log.info("--------------Progress Status: "+progressStatus);
      
      MaintWorkflowProgressForm progressForm = new MaintWorkflowProgressForm();
      progressForm.setFormData(workflowProgress);
      progressForm.setReason("Automatically run due to no response");
      
      progressDAO = null;
      
      WorkflowProgressManager progressManager = new WorkflowProgressManager(this.sessionCon, this.conn);
      WorkflowOperationManager operationManager = new WorkflowOperationManager(this.sessionCon, this.conn);
      //if the workflow step is not handled yet
      //add by nancy:"||WorkflowProgress.STATUS_IN_PROGRESS.equals(progressStatus)||WorkflowProgress.STATUS_LOCK.equals(progressStatus)"
      if (WorkflowProgress.STATUS_PENDING.equals(progressStatus)||WorkflowProgress.STATUS_IN_PROGRESS.equals(progressStatus)||WorkflowProgress.STATUS_LOCK.equals(progressStatus)){
        if (Utility.isEmpty(onNoResponseAction) || WorkflowStep.NO_RESPONSE_ACTION_KEEP.equals(onNoResponseAction)){
          // do nothing
        }else if (WorkflowStep.NO_RESPONSE_ACTION_COMPLETE.equals(onNoResponseAction)){
          progressForm.setStatus(WorkflowProgress.STATUS_GENERAL_ACCOMPLISHMENT);
          progressManager.accomplishWorkflowProgressByUser(progressForm);
        }else if (WorkflowStep.NO_RESPONSE_ACTION_APPROVE.equals(onNoResponseAction)){
          progressForm.setStatus(WorkflowProgress.STATUS_APPROVE);
          progressManager.accomplishWorkflowProgressByUser(progressForm);
        }else if (WorkflowStep.NO_RESPONSE_ACTION_REJECT.equals(onNoResponseAction)){
          progressForm.setStatus(WorkflowProgress.STATUS_REJECT);
          progressManager.accomplishWorkflowProgressByUser(progressForm);
        }else if (WorkflowStep.NO_RESPONSE_ACTION_YES.equals(onNoResponseAction)){
          progressForm.setStatus(WorkflowProgress.STATUS_YES);
          progressManager.accomplishWorkflowProgressByUser(progressForm);
        }else if (WorkflowStep.NO_RESPONSE_ACTION_NO.equals(onNoResponseAction)){
          progressForm.setStatus(WorkflowProgress.STATUS_NO);
          progressManager.accomplishWorkflowProgressByUser(progressForm);
        }else if (WorkflowStep.NO_RESPONSE_ACTION_DECISION.equals(onNoResponseAction.substring(0,1))){
          progressForm.setDecision(new String[]{WorkflowStep.PARENT_TYPE_SINGLE+onNoResponseAction.substring(1)});
          progressForm.setStatus(WorkflowProgress.STATUS_GENERAL_ACCOMPLISHMENT);
          progressManager.accomplishWorkflowProgressByUser(progressForm);
        }else if (WorkflowStep.NO_RESPONSE_ACTION_STOP.equals(onNoResponseAction)){
          //operationManager.stopWorkflowTrack(workflowProgress, workflowStep);//delete by tc
          progressForm.setStatus(WorkflowProgress.STATUS_CANCEL);
          progressManager.accomplishWorkflowProgressByUser(progressForm);//add by tc for bug-1641
        }else if (WorkflowStep.NO_RESPONSE_ACTION_ROUTE.equals(onNoResponseAction)){
          progressManager.routeToOtherStep(workflowProgress, workflowStep);
        }
      }
      conn.commit();
    }catch(Exception e){
      log.error(e, e);
    } finally {
      log.info("--------------End NoResponseWorkflowHandler-----------" );
      try { this.conn.close(); } catch (Exception ignore) {} finally { this.conn = null; }
    }
  }
}